package netty.rpc.client;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2022/5/17 8:44
 */
public class NettyRpcRequestTimeHolder {

    private static final Long CLEAN_TIME_INTERVAL = 5 * 60 * 1000L;


    private static final Map<String,Long> requestTimeOutTimeMap = new ConcurrentHashMap<>();

    public static void markRequest(String requestId,Long timeOutTime){
        requestTimeOutTimeMap.put(requestId, System.currentTimeMillis()+timeOutTime);
    }

    public static Long timeOutTime(String requestId){
        return requestTimeOutTimeMap.get(requestId);
    }

    public static void remove(String requestId){
        requestTimeOutTimeMap.remove(requestId);
    }

    static {
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(CLEAN_TIME_INTERVAL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Long now = System.currentTimeMillis();
                Iterator<Map.Entry<String, Long>> iterator = requestTimeOutTimeMap.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Long> next = iterator.next();
                    if (now > next.getValue()){
                        iterator.remove();
                    }
                }
            }
        }).start();
    }

}
